package com.spzx.user.service.impl;

import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.user.domain.Region;
import com.spzx.user.mapper.RegionMapper;
import io.reactivex.rxjava3.core.Completable;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.user.mapper.UserAddressMapper;
import com.spzx.user.domain.UserAddress;
import com.spzx.user.service.IUserAddressService;

/**
 * 用户地址Service业务层处理
 *
 * @author atguigu
 * @date 2024-09-29
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService
{
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Resource
    RegionMapper regionMapper;
    /**
     * 查询用户地址列表
     *
     * @param userAddress 用户地址
     * @return 用户地址
     */
    @Override
    public List<UserAddress> selectUserAddressList(UserAddress userAddress)
    {
        return userAddressMapper.selectUserAddressList(userAddress);
    }

    @Override
    public boolean saveUserAddress(UserAddress userAddress) {
        userAddress.setUserId(SecurityUtils.getUserId());
        //查询出省市区  拼接
        String provinceName = regionMapper.selectOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getProvinceCode())
                .select(Region::getName)
        ).getName();

        String cityName = regionMapper.selectOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getCityCode())
                .select(Region::getName)
        ).getName();
        String  districtName = regionMapper.selectOne(Wrappers.lambdaQuery(Region.class)
                .eq(Region::getCode, userAddress.getDistrictCode())
                .select(Region::getName)
        ).getName();

        userAddress.setFullAddress(provinceName+" "+cityName+" "+districtName+userAddress.getAddress());

        //如果保存的时默认地址。回合之前的默认地址冲突
        if (userAddress.getIsDefault().equals(1)){
            //更新数据库的用户地址 全部设置为非默认
            this.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .eq(UserAddress::getUserId, SecurityUtils.getUserId())
                    .eq(UserAddress::getIsDefault,1L)
                    .set(UserAddress::getIsDefault,0L));
        }

        return baseMapper.insert(userAddress)>0;
    }


}
